<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>浅谈PWA(Progressive Web App) | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="JavaScript,PWA,">
  

  <meta name="description" content="一、初识PWA  PWA，即Progressive Web App, 是提升 Web App 的体验的一种新方法，能给用户原生应用的体验。 一个 PWA 应用首先是一个网页, 可以通过 Web 技术编写出一个网页应用. 随后添加上 App Manifest 和 Service Worker 来实现PWA 的安装和离线等功能   1.1 PWA中的一些技术 PWA本身其实是一个概念集合，它不是指某一">
<meta name="keywords" content="JavaScript,PWA">
<meta property="og:type" content="article">
<meta property="og:title" content="浅谈PWA(Progressive Web App)">
<meta property="og:url" content="http://blog.poetries.top/2018/09/04/pwa/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、初识PWA  PWA，即Progressive Web App, 是提升 Web App 的体验的一种新方法，能给用户原生应用的体验。 一个 PWA 应用首先是一个网页, 可以通过 Web 技术编写出一个网页应用. 随后添加上 App Manifest 和 Service Worker 来实现PWA 的安装和离线等功能   1.1 PWA中的一些技术 PWA本身其实是一个概念集合，它不是指某一">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/401.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/402.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/403.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/404.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.930Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="浅谈PWA(Progressive Web App)">
<meta name="twitter:description" content="一、初识PWA  PWA，即Progressive Web App, 是提升 Web App 的体验的一种新方法，能给用户原生应用的体验。 一个 PWA 应用首先是一个网页, 可以通过 Web 技术编写出一个网页应用. 随后添加上 App Manifest 和 Service Worker 来实现PWA 的安装和离线等功能   1.1 PWA中的一些技术 PWA本身其实是一个概念集合，它不是指某一">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/2019/10/401.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#一、初识PWA"><span class="toc-text">一、初识PWA</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-PWA中的一些技术"><span class="toc-text">1.1 PWA中的一些技术</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-解决了哪些问题"><span class="toc-text">1.2 解决了哪些问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-3-PWA存在的问题"><span class="toc-text">1.3 PWA存在的问题</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#二、PWA的实现"><span class="toc-text">二、PWA的实现</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#2-1-Manifest实现添加至主屏幕"><span class="toc-text">2.1 Manifest实现添加至主屏幕</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-2-service-worker实现离线缓存"><span class="toc-text">2.2 service worker实现离线缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-1-什么是service-worker"><span class="toc-text">2.2.1 什么是service worker</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-2-最主要的特点"><span class="toc-text">2.2.2 最主要的特点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-3-生命周期"><span class="toc-text">2.2.3 生命周期</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-4-实现离线缓存"><span class="toc-text">2.2.4 实现离线缓存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-5-调试相关"><span class="toc-text">2.2.5 调试相关</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-3-serice-worker实现消息推送"><span class="toc-text">2.3 serice worker实现消息推送</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#三、参考"><span class="toc-text">三、参考</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-pwa" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">浅谈PWA(Progressive Web App)</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.09.04</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 3.1k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 13分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h1 id="一、初识PWA"><a href="#一、初识PWA" class="headerlink" title="一、初识PWA"></a>一、初识PWA</h1><blockquote>
<ul>
<li><code>PWA</code>，即<code>Progressive Web App</code>, 是提升 <code>Web App</code> 的体验的一种新方法，能给用户原生应用的体验。</li>
<li>一个 <code>PWA</code> 应用首先是一个网页, 可以通过 <code>Web</code> 技术编写出一个网页应用. 随后添加上 <code>App Manifest</code> 和 <code>Service Worker</code> 来实现<code>PWA</code> 的安装和离线等功能</li>
</ul>
</blockquote>
<h2 id="1-1-PWA中的一些技术"><a href="#1-1-PWA中的一些技术" class="headerlink" title="1.1 PWA中的一些技术"></a>1.1 PWA中的一些技术</h2><blockquote>
<p><code>PWA</code>本身其实是一个概念集合，它不是指某一项技术，而是通过一系列的<code>Web</code>技术与<code>Web</code>标准来优化<code>Web App</code>的安全、性能和体验。其中涉及到的一些技术概念包括了</p>
</blockquote>
<ul>
<li><code>Web App Manifest</code></li>
<li><code>Service Worker</code></li>
<li><code>Cache API</code> 缓存</li>
<li><code>Push、Notification</code> 推送与通知</li>
<li><code>Background Sync</code>后台同步</li>
<li>响应式设计</li>
</ul>
<h2 id="1-2-解决了哪些问题"><a href="#1-2-解决了哪些问题" class="headerlink" title="1.2 解决了哪些问题"></a>1.2 解决了哪些问题</h2><ul>
<li>可以添加至主屏幕，点击主屏幕图标可以实现启动动画以及隐藏地址栏</li>
<li>实现离线缓存功能，即使用户手机没有网络，依然可以使用一些离线功能</li>
<li>实现了消息推送</li>
</ul>
<h2 id="1-3-PWA存在的问题"><a href="#1-3-PWA存在的问题" class="headerlink" title="1.3 PWA存在的问题"></a>1.3 PWA存在的问题</h2><ul>
<li>支持率不高:现在<code>ios</code>手机端不支持<code>pwa</code>，<code>IE</code>也暂时不支持<br><code>Chrome</code>在中国桌面版占有率还是不错的，安卓移动端上的占有率却很低</li>
<li>各大厂商还未明确支持<code>pwa</code></li>
<li>依赖的<code>GCM</code>服务在国内无法使用</li>
<li>微信小程序的竞争</li>
</ul>
<blockquote>
<p>尽管有上述的一些缺点，PWA技术仍然有很多可以使用的点。</p>
</blockquote>
<ul>
<li><code>service worker</code>技术实现离线缓存，可以将一些不经常更改的静态文件放到缓存中，提升用户体验。</li>
<li><code>service worker</code>实现消息推送，使用浏览器推送功能，吸引用户<br>渐进式开发，尽管一些浏览器暂时不支持，可以利用上述技术给使用支持浏览器的用户带来更好的体验</li>
</ul>
<h1 id="二、PWA的实现"><a href="#二、PWA的实现" class="headerlink" title="二、PWA的实现"></a>二、PWA的实现</h1><h2 id="2-1-Manifest实现添加至主屏幕"><a href="#2-1-Manifest实现添加至主屏幕" class="headerlink" title="2.1 Manifest实现添加至主屏幕"></a>2.1 Manifest实现添加至主屏幕</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--index.html--&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Minimal PWA<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, user-scalable=no"</span> /&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"manifest"</span> <span class="attr">href</span>=<span class="string">"manifest.json"</span> /&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">type</span>=<span class="string">"text/css"</span> <span class="attr">href</span>=<span class="string">"main.css"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"icon"</span> <span class="attr">href</span>=<span class="string">"/e.png"</span> <span class="attr">type</span>=<span class="string">"image/png"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// manifest.json</span></span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  <span class="string">"name"</span>: <span class="string">"Minimal PWA"</span>, <span class="comment">// 必填 显示的插件名称</span></span><br><span class="line">  <span class="string">"short_name"</span>: <span class="string">"PWA Demo"</span>, <span class="comment">// 可选  在APP launcher和新的tab页显示，如果没有设置，则使用name</span></span><br><span class="line">  <span class="string">"description"</span>: <span class="string">"The app that helps you understand PWA"</span>, <span class="comment">//用于描述应用</span></span><br><span class="line">  <span class="string">"display"</span>: <span class="string">"standalone"</span>, <span class="comment">// 定义开发人员对Web应用程序的首选显示模式。standalone模式会有单独的</span></span><br><span class="line">  <span class="string">"start_url"</span>: <span class="string">"/"</span>, <span class="comment">// 应用启动时的url</span></span><br><span class="line">  <span class="string">"theme_color"</span>: <span class="string">"#313131"</span>, <span class="comment">// 桌面图标的背景色</span></span><br><span class="line">  <span class="string">"background_color"</span>: <span class="string">"#313131"</span>, <span class="comment">// 为web应用程序预定义的背景颜色。在启动web应用程序和加载应用程序的内容之间创建了一个平滑的过渡。</span></span><br><span class="line">  <span class="string">"icons"</span>: [ <span class="comment">// 桌面图标，是一个数组</span></span><br><span class="line">    &#123;</span><br><span class="line">    <span class="string">"src"</span>: <span class="string">"icon/lowres.webp"</span>,</span><br><span class="line">    <span class="string">"sizes"</span>: <span class="string">"48x48"</span>,  <span class="comment">// 以空格分隔的图片尺寸</span></span><br><span class="line">    <span class="string">"type"</span>: <span class="string">"image/webp"</span>  <span class="comment">// 帮助userAgent快速排除不支持的类型</span></span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="string">"src"</span>: <span class="string">"icon/lowres"</span>,</span><br><span class="line">    <span class="string">"sizes"</span>: <span class="string">"48x48"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="string">"src"</span>: <span class="string">"icon/hd_hi.ico"</span>,</span><br><span class="line">    <span class="string">"sizes"</span>: <span class="string">"72x72 96x96 128x128 256x256"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="string">"src"</span>: <span class="string">"icon/hd_hi.svg"</span>,</span><br><span class="line">    <span class="string">"sizes"</span>: <span class="string">"72x72"</span></span><br><span class="line">  &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<ul>
<li><code>Manifest</code>参考文档：<a href="https://developer.mozilla.org/zh-CN/docs/Web/Manifest" target="_blank" rel="noopener">https://developer.mozilla.org/zh-CN/docs/Web/Manifest</a></li>
<li>如果用的是安卓手机，可以下载chrome浏览器自己操作看看</li>
</ul>
</blockquote>
<h2 id="2-2-service-worker实现离线缓存"><a href="#2-2-service-worker实现离线缓存" class="headerlink" title="2.2 service worker实现离线缓存"></a>2.2 service worker实现离线缓存</h2><h3 id="2-2-1-什么是service-worker"><a href="#2-2-1-什么是service-worker" class="headerlink" title="2.2.1 什么是service worker"></a>2.2.1 什么是service worker</h3><blockquote>
<p><code>Service Worker</code> 是 Chrome 团队提出和力推的一个 WEB API，用于给 web 应用提供高级的可持续的后台处理能力</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/401.png" alt></p>
<blockquote>
<p><code>Service Workers</code> 就像介于服务器和网页之间的拦截器，能够拦截进出的HTTP 请求，从而完全控制你的网站</p>
</blockquote>
<h3 id="2-2-2-最主要的特点"><a href="#2-2-2-最主要的特点" class="headerlink" title="2.2.2 最主要的特点"></a>2.2.2 最主要的特点</h3><ul>
<li>在页面中注册并安装成功后，运行于浏览器后台，不受页面刷新的影响，可以监听和截拦作用域范围内所有页面的 <code>HTTP</code> 请求。</li>
<li>网站必须使用 <code>HTTPS</code>。除了使用本地开发环境调试时(如域名使用 <code>localhost</code>)</li>
<li>运行于浏览器后台，可以控制打开的作用域范围下所有的页面请求</li>
<li>单独的作用域范围，单独的运行环境和执行线程</li>
<li>不能操作页面 <code>DOM</code>。但可以通过事件机制来处理</li>
<li>事件驱动型服务线程</li>
</ul>
<blockquote>
<p>为什么要求网站必须是<code>HTTPS</code>的，大概是因为<code>service worker</code>权限太大能拦截所有页面的请求，如果<code>http</code>的网站安装<code>service worker</code>很容易被攻击</p>
</blockquote>
<h3 id="2-2-3-生命周期"><a href="#2-2-3-生命周期" class="headerlink" title="2.2.3 生命周期"></a>2.2.3 生命周期</h3><p><img src="https://poetries1.gitee.io/img-repo/2019/10/402.png" alt></p>
<blockquote>
<p>当用户首次导航至 URL 时，服务器会返回响应的网页。</p>
</blockquote>
<ul>
<li>第1步:当你调用 <code>register()</code> 函数时， <code>Service Worker</code>开始下载。</li>
<li>第2步:在注册过程中，浏览器会下载、解析并执行 <code>Service Worker ()</code>。如果在此步骤中出现任何错误，<code>register()</code>返回的 <code>promise</code> 都会执行 <code>reject</code>操作，并且 <code>Service Worker</code> 会被废弃。</li>
<li>第3步:一旦 <code>Service Worker</code> 成功执行了，<code>install</code> 事件就会激活</li>
<li>第4步:安装完成，<code>Service Worker</code> 便会激活，并控制在其范围内的一切。如果生命周期中的所有事件都成功了，<code>Service Worker</code>便已准备就绪，随时可以使用了！</li>
</ul>
<blockquote>
<p><code>chrome://serviceworker-internals</code> 来了解当前浏览器中所有已安装<code>Service Worker</code>的详细情况</p>
</blockquote>
<h3 id="2-2-4-实现离线缓存"><a href="#2-2-4-实现离线缓存" class="headerlink" title="2.2.4 实现离线缓存"></a>2.2.4 实现离线缓存</h3><p><strong>HTTP缓存</strong></p>
<ul>
<li><code>Web</code> 服务器可以使用 <code>Expires</code> 首部来通知 <code>Web</code>客户端，它可以使用资源的当前副本，直到指定的“过期时间”。反过来，浏览器可以缓存此资源，并且只有在有效期满后才会再次检查新版本。使用 <code>HTTP</code> 缓存意味着你要依赖服务器来告诉你何时缓存资源和何时过期</li>
</ul>
<p><strong>service worker缓存</strong></p>
<ul>
<li><code>Service Workers</code>的强大在于它们拦截 HTTP 请求的能力<br>进入任何传入的<code>HTTP</code> 请求，并决定想要如何响应。在你的 <code>Service Worker</code> 中，可以编写逻辑来决定想要缓存的资源，以及需要满足什么条件和资源需要缓存多久。一切尽归你掌控！</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--index.html--&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Hello Caching World!<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Image --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"/images/hello.png"</span> /&gt;</span>                 </span><br><span class="line">    <span class="comment">&lt;!-- JavaScript --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">async</span> <span class="attr">src</span>=<span class="string">"/js/script.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span>     </span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">      <span class="comment">// 注册 service worker</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">if</span> (<span class="string">'serviceWorker'</span> <span class="keyword">in</span> navigator) &#123;           </span></span><br><span class="line"><span class="javascript">        navigator.serviceWorker.register(<span class="string">'/service-worker.js'</span>, &#123;<span class="attr">scope</span>: <span class="string">'/'</span>&#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params">registration</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">          <span class="comment">// 注册成功</span></span></span><br><span class="line"><span class="javascript">          <span class="built_in">console</span>.log(<span class="string">'ServiceWorker registration successful with scope: '</span>, registration.scope);</span></span><br><span class="line"><span class="javascript">        &#125;).catch(<span class="function"><span class="keyword">function</span> (<span class="params">err</span>) </span>&#123;                   </span></span><br><span class="line"><span class="javascript">          <span class="comment">// 注册失败 :(</span></span></span><br><span class="line"><span class="javascript">          <span class="built_in">console</span>.log(<span class="string">'ServiceWorker registration failed: '</span>, err);</span></span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>注：<code>Service Worker</code>的注册路径决定了其 <code>scope</code>默认作用页面的范围。</li>
<li>如果 <code>service-worker.js</code>是在 <code>/sw/</code> 页面路径下，这使得该 <code>Service Worker</code> 默认只会收到 页面<code>/sw/</code> 路径下的 fetch 事件。</li>
<li>如果存放在网站的根路径下，则将会收到该网站的所有 <code>fetch</code>事件。</li>
<li>如果希望改变它的作用域，可在第二个参数设置 <code>scope</code> 范围。示例中将其改为了根目录，即对整个站点生效。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// service-worker.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> cacheName = <span class="string">'helloWorld'</span>;     <span class="comment">// 缓存的名称  </span></span><br><span class="line"><span class="comment">// install 事件，它发生在浏览器安装并注册 Service Worker 时        </span></span><br><span class="line">self.addEventListener(<span class="string">'install'</span>, event =&gt; &#123; </span><br><span class="line"><span class="comment">/* event.waitUtil 用于在安装成功之前执行一些预装逻辑</span></span><br><span class="line"><span class="comment"> 但是建议只做一些轻量级和非常重要资源的缓存，减少安装失败的概率</span></span><br><span class="line"><span class="comment"> 安装成功后 ServiceWorker 状态会从 installing 变为 installed */</span></span><br><span class="line">  event.waitUntil(</span><br><span class="line">    caches.open(cacheName)                  </span><br><span class="line">    .then(<span class="function"><span class="params">cache</span> =&gt;</span> cache.addAll([    <span class="comment">// 如果所有的文件都成功缓存了，便会安装完成。如果任何文件下载失败了，那么安装过程也会随之失败。        </span></span><br><span class="line">      <span class="string">'/js/script.js'</span>,</span><br><span class="line">      <span class="string">'/images/hello.png'</span></span><br><span class="line">    ]))</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br><span class="line">  </span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">为 fetch 事件添加一个事件监听器。接下来，使用 caches.match() 函数来检查传入的请求 URL 是否匹配当前缓存中存在的任何内容。如果存在的话，返回缓存的资源。</span></span><br><span class="line"><span class="comment">如果资源并不存在于缓存当中，通过网络来获取资源，并将获取到的资源添加到缓存中。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">self.addEventListener(<span class="string">'fetch'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">event</span>) </span>&#123;</span><br><span class="line">  event.respondWith(</span><br><span class="line">    caches.match(event.request)                  </span><br><span class="line">    .then(<span class="function"><span class="keyword">function</span> (<span class="params">response</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (response) &#123;                            </span><br><span class="line">        <span class="keyword">return</span> response;                         </span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">var</span> requestToCache = event.request.clone();  <span class="comment">//          </span></span><br><span class="line">      <span class="keyword">return</span> fetch(requestToCache).then(                   </span><br><span class="line">        <span class="function"><span class="keyword">function</span> (<span class="params">response</span>) </span>&#123;</span><br><span class="line">          <span class="keyword">if</span> (!response || response.status !== <span class="number">200</span>) &#123;      </span><br><span class="line">            <span class="keyword">return</span> response;</span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">var</span> responseToCache = response.clone();          </span><br><span class="line">          caches.open(cacheName)                           </span><br><span class="line">            .then(<span class="function"><span class="keyword">function</span> (<span class="params">cache</span>) </span>&#123;</span><br><span class="line">              cache.put(requestToCache, responseToCache);  </span><br><span class="line">            &#125;);</span><br><span class="line">          <span class="keyword">return</span> response;             </span><br><span class="line">    &#125;)</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注：为什么用<code>request.clone()</code>和<code>response.clone()</code><br>需要这么做是因为<code>request</code>和<code>response</code>是一个流，它只能消耗一次。因为我们已经通过缓存消耗了一次，然后发起 <code>HTTP</code> 请求还要再消耗一次，所以我们需要在此时克隆请求<br>Clone the request—a request is a stream and can only be consumed once</p>
</blockquote>
<h3 id="2-2-5-调试相关"><a href="#2-2-5-调试相关" class="headerlink" title="2.2.5 调试相关"></a>2.2.5 调试相关</h3><blockquote>
<p>chrome浏览器打开<code>https://googlechrome.github.io/samples/service-worker/basic/index.html</code>，这是一个实现了<code>service worker</code>离线缓存功能的网站，打开调试工具</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/403.png" alt></p>
<ul>
<li>勾选可以模拟网站离线情况，勾选后<code>network</code>会有一个黄色警告图标，该网站已经离线。此时刷新页面，页面仍然能够正常显示</li>
<li>当前<code>service worker</code>的<code>scope</code>。它能够拦截<code>https://googlechrome.github.i</code>…，同样也能够拦截<code>https://googlechrome.github.i.</code>..<em>/</em>.html下的请求</li>
</ul>
<blockquote>
<p>调试面板具体代表的什么参看 <code>https://x5.tencent.com/tbs/guide/serviceworker.html</code>的第三部分</p>
</blockquote>
<h2 id="2-3-serice-worker实现消息推送"><a href="#2-3-serice-worker实现消息推送" class="headerlink" title="2.3 serice worker实现消息推送"></a>2.3 serice worker实现消息推送</h2><p><img src="https://poetries1.gitee.io/img-repo/2019/10/404.png" alt></p>
<ul>
<li>步骤一、提示用户并获得他们的订阅详细信息</li>
<li>步骤二、将这些详细信息保存在服务器上</li>
<li>步骤三、在需要时发送任何消息</li>
</ul>
<blockquote>
<p>不同浏览器需要用不同的推送消息服务器。以 Chrome 上使用 <code>Google Cloud Messaging&lt;GCM&gt;</code> 作为推送服务为例，第一步是注册 <code>applicationServerKey</code>(通过 GCM 注册获取)，并在页面上进行订阅或发起订阅。每一个会话会有一个独立的端点（<code>endpoint</code>），订阅对象的属性(<code>PushSubscription.endpoint</code>) 即为端点值。将端点发送给服务器后，服务器用这一值来发送消息给会话的激活的 Service Worker （通过 GCM 与浏览器客户端沟通</p>
</blockquote>
<p><strong>步骤一和步骤二</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--index.html--&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Progressive Times<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"manifest"</span> <span class="attr">href</span>=<span class="string">"/manifest.json"</span>&gt;</span>                                      </span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">var</span> endpoint;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">var</span> key;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">var</span> authSecret;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">var</span> vapidPublicKey = <span class="string">'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY'</span>;</span></span><br><span class="line"><span class="javascript">      <span class="comment">// 方法很复杂，但是可以不用具体看，知识用来转化vapidPublicKey用</span></span></span><br><span class="line"><span class="javascript">      <span class="function"><span class="keyword">function</span> <span class="title">urlBase64ToUint8Array</span>(<span class="params">base64String</span>) </span>&#123;                                  </span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> padding = <span class="string">'='</span>.repeat((<span class="number">4</span> - base64String.length % <span class="number">4</span>) % <span class="number">4</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> base64 = (base64String + padding)</span></span><br><span class="line"><span class="javascript">          .replace(<span class="regexp">/\-/g</span>, <span class="string">'+'</span>)</span></span><br><span class="line"><span class="javascript">          .replace(<span class="regexp">/_/g</span>, <span class="string">'/'</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> rawData = <span class="built_in">window</span>.atob(base64);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> outputArray = <span class="keyword">new</span> <span class="built_in">Uint8Array</span>(rawData.length);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; rawData.length; ++i) &#123;</span></span><br><span class="line">          outputArray[i] = rawData.charCodeAt(i);</span><br><span class="line">        &#125;</span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> outputArray;</span></span><br><span class="line">      &#125;</span><br><span class="line"><span class="javascript">      <span class="keyword">if</span> (<span class="string">'serviceWorker'</span> <span class="keyword">in</span> navigator) &#123;</span></span><br><span class="line"><span class="javascript">        navigator.serviceWorker.register(<span class="string">'sw.js'</span>).then(<span class="function"><span class="keyword">function</span> (<span class="params">registration</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">          <span class="keyword">return</span> registration.pushManager.getSubscription()                            </span></span><br><span class="line"><span class="javascript">            .then(<span class="function"><span class="keyword">function</span> (<span class="params">subscription</span>) </span>&#123;</span></span><br><span class="line">              if (subscription) &#123;                                                      </span><br><span class="line"><span class="javascript">                <span class="keyword">return</span>;</span></span><br><span class="line">              &#125;</span><br><span class="line"><span class="javascript">              <span class="keyword">return</span> registration.pushManager.subscribe(&#123;                              </span></span><br><span class="line"><span class="javascript">                  userVisibleOnly: <span class="literal">true</span>,</span></span><br><span class="line">                  applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)</span><br><span class="line">                &#125;)</span><br><span class="line"><span class="javascript">                .then(<span class="function"><span class="keyword">function</span> (<span class="params">subscription</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                  <span class="keyword">var</span> rawKey = subscription.getKey ? subscription.getKey(<span class="string">'p256dh'</span>) : <span class="string">''</span>;</span></span><br><span class="line"><span class="javascript">                  key = rawKey ? btoa(<span class="built_in">String</span>.fromCharCode.apply(<span class="literal">null</span>, <span class="keyword">new</span> <span class="built_in">Uint8Array</span>(rawKey))) : <span class="string">''</span>;</span></span><br><span class="line"><span class="javascript">                  <span class="keyword">var</span> rawAuthSecret = subscription.getKey ? subscription.getKey(<span class="string">'auth'</span>) : <span class="string">''</span>;</span></span><br><span class="line">                  authSecret = rawAuthSecret ?</span><br><span class="line"><span class="javascript">                    btoa(<span class="built_in">String</span>.fromCharCode.apply(<span class="literal">null</span>, <span class="keyword">new</span> <span class="built_in">Uint8Array</span>(rawAuthSecret))) : <span class="string">''</span>;</span></span><br><span class="line">                  endpoint = subscription.endpoint;</span><br><span class="line"><span class="javascript">                  <span class="keyword">return</span> fetch(<span class="string">'./register'</span>, &#123;                                         </span></span><br><span class="line"><span class="javascript">                    method: <span class="string">'post'</span>,</span></span><br><span class="line"><span class="javascript">                    headers: <span class="keyword">new</span> Headers(&#123;</span></span><br><span class="line"><span class="javascript">                      <span class="string">'content-type'</span>: <span class="string">'application/json'</span></span></span><br><span class="line">                    &#125;),</span><br><span class="line"><span class="javascript">                    body: <span class="built_in">JSON</span>.stringify(&#123;</span></span><br><span class="line">                      endpoint: subscription.endpoint,</span><br><span class="line">                      key: key,</span><br><span class="line">                      authSecret: authSecret,</span><br><span class="line">                    &#125;),</span><br><span class="line">                  &#125;);</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125;);</span><br><span class="line"><span class="javascript">        &#125;).catch(<span class="function"><span class="keyword">function</span> (<span class="params">err</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">          <span class="comment">// 注册失败 :(</span></span></span><br><span class="line"><span class="javascript">          <span class="built_in">console</span>.log(<span class="string">'ServiceWorker registration failed: '</span>, err);</span></span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>步骤三 服务器发送消息给service worker</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> webpush = <span class="built_in">require</span>(<span class="string">'web-push'</span>);                 </span><br><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">var</span> bodyParser = <span class="built_in">require</span>(<span class="string">'body-parser'</span>);</span><br><span class="line"><span class="keyword">const</span> app = express();</span><br><span class="line">webpush.setVapidDetails(                             </span><br><span class="line">  <span class="string">'mailto:contact@deanhume.com'</span>,</span><br><span class="line">  <span class="string">'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY'</span>,</span><br><span class="line">  <span class="string">'p6YVD7t8HkABoez1CvVJ5bl7BnEdKUu5bSyVjyxMBh0'</span></span><br><span class="line">);</span><br><span class="line">app.post(<span class="string">'/register'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;           </span><br><span class="line">  <span class="keyword">var</span> endpoint = req.body.endpoint;</span><br><span class="line">  saveRegistrationDetails(endpoint, key, authSecret); </span><br><span class="line">  <span class="keyword">const</span> pushSubscription = &#123;                          </span><br><span class="line">    endpoint: req.body.endpoint,</span><br><span class="line">    keys: &#123;</span><br><span class="line">      auth: req.body.authSecret,</span><br><span class="line">      p256dh: req.body.key</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">var</span> body = <span class="string">'Thank you for registering'</span>;</span><br><span class="line">  <span class="keyword">var</span> iconUrl = <span class="string">'https://example.com/images/homescreen.png'</span>;</span><br><span class="line">  <span class="comment">// 发送 Web 推送消息</span></span><br><span class="line">  webpush.sendNotification(pushSubscription,          </span><br><span class="line">      <span class="built_in">JSON</span>.stringify(&#123;</span><br><span class="line">        msg: body,</span><br><span class="line">        url: <span class="string">'http://localhost:3111/'</span>,</span><br><span class="line">        icon: iconUrl</span><br><span class="line">      &#125;))</span><br><span class="line">    .then(<span class="function"><span class="params">result</span> =&gt;</span> res.sendStatus(<span class="number">201</span>))</span><br><span class="line">    .catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(err);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line">app.listen(<span class="number">3111</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'Web push app listening on port 3111!'</span>)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>service worker</code>监听push事件，将通知详情推送给用户</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// service-worker.js</span></span><br><span class="line"></span><br><span class="line">self.addEventListener(<span class="string">'push'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">event</span>) </span>&#123;</span><br><span class="line"> <span class="comment">// 检查服务端是否发来了任何有效载荷数据</span></span><br><span class="line">  <span class="keyword">var</span> payload = event.data ? <span class="built_in">JSON</span>.parse(event.data.text()) : <span class="string">'no payload'</span>;</span><br><span class="line">  <span class="keyword">var</span> title = <span class="string">'Progressive Times'</span>;</span><br><span class="line">  event.waitUntil(</span><br><span class="line">    <span class="comment">// 使用提供的信息来显示 Web 推送通知</span></span><br><span class="line">    self.registration.showNotification(title, &#123;                           </span><br><span class="line">      body: payload.msg,</span><br><span class="line">      url: payload.url,</span><br><span class="line">      icon: payload.icon</span><br><span class="line">    &#125;)</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h1 id="三、参考"><a href="#三、参考" class="headerlink" title="三、参考"></a>三、参考</h1><ul>
<li><a href="https://lzw.me/a/pwa-service-worker.html#3.3" target="_blank" rel="noopener">网站渐进式增强体验(PWA)改造：Service Worker 应用详解</a></li>
<li><a href="https://github.com/SangKa/PWA-Book-CN" target="_blank" rel="noopener">PWA实战：面向下一代的Progressive Web APP</a></li>
<li><a href="https://x5.tencent.com/tbs/guide/serviceworker.html" target="_blank" rel="noopener">Service Worker最佳实践</a></li>
<li><a href="https://fed.renren.com/2017/10/04/service-worker/" target="_blank" rel="noopener">使用 Service Worker 做一个 PWA 离线网页应用</a></li>
<li><a href="https://zhuanlan.zhihu.com/p/28461857" target="_blank" rel="noopener">理解Service Worker</a></li>
<li><a href="http://obkoro1.com/web_accumulate/accumulate/JS/webWorker%E4%B8%8A%E6%89%8B.html" target="_blank" rel="noopener">前端er来学习一下 WebWorker </a></li>
<li><a href="https://juejin.im/post/5bf3f656e51d45338e084044?utm_source=gold_browser_extension" target="_blank" rel="noopener">Service Worker学习与实践（二）——PWA简介</a></li>
<li><a href="https://juejin.im/post/5bf3f6b2e51d45360069e527?utm_source=gold_browser_extension" target="_blank" rel="noopener">Service Worker学习与实践（三）——消息推送</a></li>
<li><a href="https://github.com/nicejade/nice-front-end-tutorial/blob/master/tutorial/pwa-tutorial.md" target="_blank" rel="noopener">pwa-tutoria</a></li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/09/04/webpack-custom-work-flow/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/09/05/dva/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
